package org.amse.Archiver.model;

import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

@SuppressWarnings("serial")
public class SystemViewModel extends AbstractTableModel {
    protected ColumnDescriptor cols[] =  {
    	      new ColumnDescriptor("Name", 40, JLabel.LEFT),
    	      new ColumnDescriptor("Size", 50, JLabel.LEFT),
    	      new ColumnDescriptor("Type", 50, JLabel.LEFT),
    	      new ColumnDescriptor("Modified", 50, JLabel.LEFT),
    	    };
    	    protected ArrayList<File> fileObjects;

    	    public SystemViewModel() {
    	      fileObjects = new ArrayList<File>();
    	    }

    	    public void addData(ArrayList<File> v) {
    	      fileObjects.clear();
    	      fileObjects.addAll(v);
    	      updateObjects();
    	    }
    	    private String getFileType(File f){
    			if(!f.isDirectory()){
    				String name = f.getName();
    				int key = name.lastIndexOf(".");
    				if (key < 0) { return "File";}
    				return name.substring(key);
    			} else {
    				return "Directory";
    			}
    		}
    	    public File getFileAt(int row) {return (File)fileObjects.get(row);}
    	    protected void updateObjects() {fireTableDataChanged();}
    	    public int getColumnCount() {return(cols.length);}
    	    public int getRowCount() {return(fileObjects.size());}
    	    public String getColumnName(int c) {return(cols[c].name);}
    	    public Object getValueAt(int row, int col) {
    	      if(getRowCount() <= 0)
    	        return "";
    	      if(row < 0 || row >= getRowCount())
    	        return "";
    	      File fd = fileObjects.get(row);
    	        switch(col) {
    	          case 0: return fd.getName();
    	          case 1: return fd.length();
    	          case 2: return getFileType(fd);
    	          case 3: return new Date(fd.lastModified());
    	        }
    	      
    	      return "";
    	    }

    	    class ColumnDescriptor {
    	      public String name;
    	      public int width;
    	      public int alignment;
    	      public ColumnDescriptor(String n, int w, int a) {
    	    	  name = n;
    	    	  width = w;
    	    	  alignment = a;
    	      }
    	    }
    	  }

    	  class FileUI {
    	    private String fileName;
    	    public FileUI( String fn) {fileName = fn;}
    	    public String getFileName() {return(fileName);}
    	    public String toString() {return(fileName);}
    	  }
    	  @SuppressWarnings("serial")
		 class FileRenderer extends DefaultTableCellRenderer {
    	    public void setValue(Object cell) {
    	      if(cell instanceof FileUI) {
    	        FileUI fui = (FileUI)cell;
    	        setText(fui.getFileName());
    	        setToolTipText(fui.getFileName());
    	      }
    	      else {
    	        super.setValue(cell);
    	        setToolTipText(cell.toString());
    	      }
    	    }
    	    
    	  }